package com.boot.controller;

import com.boot.entity.*;
import com.boot.service.ISupplierManagementService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.security.auth.login.CredentialNotFoundException;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 供应商管理Controller
 */
@Controller
@RequestMapping("/supplier")
public class SupplierManagementController {

    @Autowired
    private ISupplierManagementService service;

    /**
     * 查询分公司下所有合作供应商
     *
     * @param pageIndex
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/queryAllSupplier")
    public String queryAllSupplier(String supplierName,HttpSession session, Integer pageIndex, Integer pageSize, Model model) {
        User user=(User)session.getAttribute("loginUser");
        if(user == null){
            return "login";
        }
        int companyId=user.getCompanyId();
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        if(supplierName!=null){
            if(supplierName.equals("")){
                supplierName=null;
            }
        }
        PageHelper.startPage(pageIndex, pageSize);
        try {
            List<Map<String, Object>> supplierList = service.queryAllSupplier(companyId,supplierName);
            model.addAttribute("supplierList", supplierList);
            int count = service.countSupplierList(companyId,supplierName);
            int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            model.addAttribute("pageNum", pageNum); //分页数量
            model.addAttribute("currentPage", pageIndex); //当前页面
            model.addAttribute("pageSize", pageSize); //页面数据条数
            model.addAttribute("supplierName",supplierName);
            return "cooperationList";
        } catch (Exception e) {
            System.out.println(e.toString());
            return "commons/503";
        }
    }

    /**
     * 查询指定ID的供应商成为分公司合作供应商的审核记录
     *
     * @param supplierId
     * @param model
     * @return
     */
    @RequestMapping("/querySupplierDetails/{supplierId}")
    public String querySupplierDetails(HttpSession session, @PathVariable int supplierId, Model model) {
        User user=(User)session.getAttribute("loginUser");
        if(user == null){
            return "login";
        }
        int companyId=user.getCompanyId();
        Map<String,Object> supplierMap = service.querySupplierDetails(supplierId);
        List<Map<String, Object>> check = service.queryCheck(supplierId, companyId);
        model.addAttribute("companyId", companyId);
        model.addAttribute("supplierMap", supplierMap);
        model.addAttribute("check", check);
        return "supplierDetails";
    }

    /**
     * 查询供应商成为公司合作供应商的审核申请列表
     *
     * @return
     */
    @RequestMapping("/queryCompanyApply")
    public String queryCompanyApply(String auditStatus,String supplierName,HttpSession session, Integer pageIndex, Integer pageSize, Model model) {
        User user=(User)session.getAttribute("loginUser");
        if(user == null){
            return "login";
        }
        int companyId=user.getCompanyId();
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        if(auditStatus!=null){
            if(auditStatus.equals("all")){
                auditStatus=null;
            }
        }
        if(supplierName!=null){
            if(supplierName.equals("")){
                supplierName=null;
            }
        }
        PageHelper.startPage(pageIndex, pageSize);

        List<Map<String, Object>> beCSupplierList = service.queryCompanyApply(companyId,auditStatus,supplierName);
        model.addAttribute("beCSupplierList", beCSupplierList);
        model.addAttribute("supplierName", supplierName);
        model.addAttribute("auditStatus", auditStatus);
        int count = service.countCompanyApply(companyId,auditStatus,supplierName);   //此处有问题，分页导致size最大值为7
        int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        model.addAttribute("pageNum", pageNum); //分页数量
        model.addAttribute("currentPage", pageIndex); //当前页面
        model.addAttribute("pageSize", pageSize); //页面数据条数
        return "companyApplyList";
    }

    /**
     * 审核供应商申请成为合作供应商
     *
     * @return
     */
    @RequestMapping("/queryCompanyApplyCheck/{supplierId}/{csId}")
    public String queryCompanyApplyCheck(@PathVariable int supplierId,@PathVariable int csId,Model model) {
        //供应商基本信息
        Map<String,Object> supplierMap=service.querySupplierDetails(supplierId);
        model.addAttribute("supplierMap",supplierMap);
        Map<String,Object> beCSupplierMap=service.queryCompanyApplyById(csId);
        model.addAttribute("beCSupplierMap",beCSupplierMap);
        return "companyApplyCheck";
    }

    /**
     * 查询供应商申请成为合作供应商
     * @param supplierId
     * @param model
     * @return
     */
    @RequestMapping("/queryCompanyApplyDetail/{supplierId}")
    public String queryCompanyApplyDetail(HttpSession session,@PathVariable int supplierId,Model model) {
        User user=(User)session.getAttribute("loginUser");
        if(user == null){
            return "login";
        }
        int companyId=user.getCompanyId();
        Map<String,Object> supplierMap=service.querySupplierDetails(supplierId);
        model.addAttribute("supplierMap",supplierMap);
        List<Map<String, Object>> check = service.queryCheck(supplierId, companyId);
        model.addAttribute("check", check);

        return "companyApplydetails";
    }
    /**
     * 查询电厂推荐供应商申请列表
     *
     * @param pageIndex
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/queryPowerApply")
    public String queryPowerApply(String auditStatus,String supplierName,HttpSession session,Integer pageIndex, Integer pageSize, Model model) {
        User user=(User)session.getAttribute("loginUser");
        if(user == null){
            return "login";
        }
        int companyId=user.getCompanyId();
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        if(auditStatus!=null){
            if(auditStatus.equals("all")){
                auditStatus=null;
            }
        }
        if(supplierName!=null){
            if(supplierName.equals("")){
                supplierName=null;
            }
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> bePSupplierList = service.queryPowerApply(companyId,auditStatus,supplierName);
        model.addAttribute("bePSupplierList", bePSupplierList);
        model.addAttribute("auditStatus", auditStatus);
        model.addAttribute("supplierName", supplierName);

        int count = service.countPowerApply(companyId,auditStatus,supplierName);
        int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        model.addAttribute("pageNum", pageNum); //分页数量
        model.addAttribute("currentPage", pageIndex); //当前页面
        model.addAttribute("pageSize", pageSize); //页面数据条数
        return "PowerPlantApplyList";
    }

    /**
     * 审核推荐供应商
     * @param bePSupplierId
     * @param supplierId
     * @param model
     * @return
     */
    @RequestMapping("/powerApplyCheck/{bePSupplierId}/{supplierId}")
    public String powerApplyCheck(@PathVariable int bePSupplierId,@PathVariable int supplierId,Model model){
        Map<String,Object> supplierMap=service.querySupplierDetails(supplierId);
        model.addAttribute("supplierMap",supplierMap);
        Map<String,Object> powerApplyMap=service.queryPowerApplyById(bePSupplierId);
        model.addAttribute("powerApplyMap",powerApplyMap);
        return "powerApplyCheck";
    }
    /**
     * 查询所有拉黑申请
     *
     * @param pageIndex
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/queryBlackApply")
    public String queryBlackApply(String auditStatus,String supplierName, HttpSession session,Integer pageIndex, Integer pageSize, Model model) {
        User user=(User)session.getAttribute("loginUser");
        if(user == null){
            return "login";
        }
        int companyId=user.getCompanyId();
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        if(auditStatus!=null){
            if(auditStatus.equals("all")){
                auditStatus=null;
            }
        }
        if(supplierName!=null){
            if(supplierName.equals("")){
                supplierName=null;
            }
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> blackApplyList = service.queryBlackApply(companyId,auditStatus,supplierName);
        model.addAttribute("blackApplyList", blackApplyList);
        model.addAttribute("auditStatus", auditStatus);
        model.addAttribute("supplierName", supplierName);

        int count = service.countBlackApply(companyId,auditStatus,supplierName);
        int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        model.addAttribute("pageNum", pageNum); //分页数量
        model.addAttribute("currentPage", pageIndex); //当前页面
        model.addAttribute("pageSize", pageSize); //页面数据条数
        return "blackApplyList";
    }

    /**
     * 审核电厂拉黑申请
     * @return
     */
    @RequestMapping("/blackApplyCheck/{supplierId}/{blacklistId}")
    public String blackApplyCheck(@PathVariable("supplierId") int supplierId,@PathVariable("blacklistId")int blacklistId,Model model){
        Map<String,Object> supplierMap=service.querySupplierDetails(supplierId);
        model.addAttribute("supplierMap",supplierMap);
        Map<String,Object> blackApplyMap=service.queryBlackApplyById(blacklistId);
        model.addAttribute("blackApplyMap",blackApplyMap);
        return "blackApplyCheck";
    }

    /**
     * 查看电厂拉黑申请审核记录
     * @param supplierId
     * @param blacklistId
     * @param model
     * @return
     */
    @RequestMapping("/queryBlackApplyDetails/{supplierId}/{blacklistId}")
    public String queryBlackApplyDetails(@PathVariable("supplierId") int supplierId,@PathVariable("blacklistId")int blacklistId,Model model){
        Map<String,Object> supplierMap=service.querySupplierDetails(supplierId);
        model.addAttribute("supplierMap",supplierMap);
        Map<String,Object> blackCheckMap=service.queryBlackApplyCheck(blacklistId);
        model.addAttribute("blackCheckMap",blackCheckMap);
        return "blackApplyDetails";
    }

    /**
     * 查看年度评价记录
     * @param years
     * @param pageIndex
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/queryYearScore")
    public String queryYearScore(String supplierName, HttpSession session,Integer years, Integer pageIndex, Integer pageSize, Model model) {
        User user=(User)session.getAttribute("loginUser");
        if(user == null){
            return "login";
        }
        int companyId=user.getCompanyId();
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        if(supplierName!=null){
            if(supplierName.equals("")){
                supplierName=null;
            }
        }
        if (years == null) {
            Calendar cal = Calendar.getInstance();
            years = cal.get(Calendar.YEAR);
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> yearScoreList = service.queryYearScore(years, companyId,supplierName);
        model.addAttribute("yearScoreList", yearScoreList);
        model.addAttribute("supplierName", supplierName);
        model.addAttribute("years", years);

        int count = service.countYearScore(years, companyId,supplierName);
        int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        model.addAttribute("pageNum", pageNum); //分页数量
        model.addAttribute("currentPage", pageIndex); //当前页面
        model.addAttribute("pageSize", pageSize); //页面数据条数
        return "yearScore";
    }

    @RequestMapping("/queryMonthScore/{supplierId}/{years}")
    public String queryMonthScore(@PathVariable int supplierId, @PathVariable int years, Model model) {
        List<Map<String, Object>> allMonthScore = service.queryMonthScore(supplierId, years);
        Map<String, Map<String, Object>> monthScoreMap = new HashMap<>();
        for (int i = 0; i < allMonthScore.size(); i++) {
            Map<String, Object> map = allMonthScore.get(i);
            String companyName = (String) map.get("company_name");
            Map<String, Object> map2 = new HashMap<>();
            String month;
            Integer score;
            Integer countScore=0;
            int j=0;
            while (companyName.equals((String) allMonthScore.get(i + 1).get("company_name"))) {
                 month = String.valueOf(map.get("months")) ;
                 score = (Integer) map.get("score");
                 j++;
                 countScore+=score;
                map2.put(month, score);
                i++;
                if (i == allMonthScore.size() - 1) {
                    break;
                }
                map = allMonthScore.get(i);
                companyName = (String) map.get("company_name");

            }
            map = allMonthScore.get(i);
            month = String.valueOf(map.get("months")) ;
            score = (Integer) map.get("score");
            j++;
            map2.put(month, score);
            countScore+=score;
            map2.put("sum",countScore/j);
            monthScoreMap.put(companyName, map2);
        }
        model.addAttribute("monthScoreMap", monthScoreMap);
        return "monthScore";
    }

    @RequestMapping("/companyApplyCheck")
    @ResponseBody
    public Object companyApplyCheck(CSCheck csCheck, BeCSupplier beCSupplier, int supplierId, String supplierType, HttpSession session){
        User user=(User)session.getAttribute("loginUser");
        Map<String,Object> map=new HashMap<>();
        if (user == null) {
            map.put("msg", "用户信息为空");
            map.put("code", 601);
        }else{
            service.updataBeCSupplier(beCSupplier);
            csCheck.setAuditorId(user.getId());
            service.saveCompanyApplyCheck(csCheck);
            if(csCheck.getAuditStatus().equals("agree")){
                int companyId=user.getCompanyId();
                CompanySupplier cSupplier=new CompanySupplier();
                cSupplier.setCompanyId(companyId);
                cSupplier.setSupplierId(supplierId);
                cSupplier.setSupplierType(supplierType);
                cSupplier.setCooperationRange("all");
                cSupplier.setCooperationTime(csCheck.getAuditTime());
                service.saveCompanySupplier(cSupplier);

                PowerPlantSupplier pSupplier=new PowerPlantSupplier();
                pSupplier.setSupplierId(supplierId);
                pSupplier.setSupplierType(supplierType);
                pSupplier.setCooperationTime(csCheck.getAuditTime());
                List<Integer> powerId=service.queryAllPowerId(companyId);
                for (int id:powerId) {
                    pSupplier.setCompanyId(id);
                    service.savePowerSupplier(pSupplier);
                }
                map.put("msg","通过审核已完成");
            }else {
                map.put("msg","已驳回申请");
            }

            map.put("code", 200);
        }
        return map;
    }

    @RequestMapping("/powerApplyCheck")
    @ResponseBody
    public Object powerApplyCheck(BePSupplier bePSupplier,PSCheck psCheck,HttpSession session){
        User user=(User)session.getAttribute("loginUser");
        Map<String,Object> map=new HashMap<>();
        if (user == null) {
            map.put("msg", "请先登录");
            map.put("code", 601);
        }else{
            service.updataBePSupplier(bePSupplier);
            psCheck.setAuditorId(user.getId());
            service.savePSCheck(psCheck);
            if(psCheck.getAuditStatus().equals("agree")){//同意申请
                int companyId=user.getCompanyId();
                int supplierId=bePSupplier.getSupplierId();
                if(psCheck.getQuaScope().equals("all")){  //成为公司合作供应商
                    CompanySupplier cSupplier=service.queryCompanySupplier(companyId,supplierId);
                    if(cSupplier==null){
                        cSupplier=new CompanySupplier();
                        cSupplier.setCompanyId(companyId);
                        cSupplier.setSupplierId(supplierId);
                        cSupplier.setCooperationRange("all");
                        cSupplier.setCooperationTime(psCheck.getAuditTime());
                        cSupplier.setSupplierType(bePSupplier.getSupplierType());
                        service.saveCompanySupplier(cSupplier);

                        //成为旗下所有电厂的供应商
                        PowerPlantSupplier pSupplier=new PowerPlantSupplier();
                        pSupplier.setSupplierId(supplierId);
                        pSupplier.setSupplierType(bePSupplier.getSupplierType());
                        pSupplier.setCooperationTime(psCheck.getAuditTime());
                        List<Integer> powerId=service.queryAllPowerId(companyId);
                        for (int id:powerId) {
                            pSupplier.setCompanyId(id);
                            service.savePowerSupplier(pSupplier);
                        }
                    }else{
                        if(cSupplier.getCooperationRange().equals("section")){
                            cSupplier.setCooperationRange("all");
                            cSupplier.setBlack(0);
                            service.updataCompanySupplier(cSupplier);

                            //成为剩余电厂的供应商
                            List<Integer> powerId=service.queryAllPowerId(companyId);
                            List<Integer> powerSupplierId=service.queryPowerSupplierId(companyId,supplierId);
                            powerId.removeAll(powerSupplierId);
                            if(powerId.size()>0){
                                PowerPlantSupplier pSupplier=new PowerPlantSupplier();
                                pSupplier.setSupplierId(supplierId);
                                pSupplier.setSupplierType(bePSupplier.getSupplierType());
                                pSupplier.setCooperationTime(psCheck.getAuditTime());
                                for (int id:powerId) {
                                    pSupplier.setCompanyId(id);
                                    service.savePowerSupplier(pSupplier);
                                }
                            }
                        }
                    }
                }else{  //成为电厂合作供应商
                    PowerPlantSupplier pSupplier=new PowerPlantSupplier();
                    pSupplier.setCompanyId(bePSupplier.getCompanyId());
                    pSupplier.setSupplierId(supplierId);
                    pSupplier.setSupplierType(bePSupplier.getSupplierType());
                    pSupplier.setCooperationTime(psCheck.getAuditTime());
                    service.savePowerSupplier(pSupplier);

                    CompanySupplier cSupplier=service.queryCompanySupplier(companyId,supplierId);
                    //未曾与公司合作过
                    if(cSupplier==null){
                        cSupplier=new CompanySupplier();
                        cSupplier.setCompanyId(companyId);
                        cSupplier.setSupplierId(supplierId);
                        cSupplier.setCooperationRange("section");
                        cSupplier.setCooperationTime(psCheck.getAuditTime());
                        cSupplier.setSupplierType(bePSupplier.getSupplierType());
                        service.saveCompanySupplier(cSupplier);
                    }else{
                        //最后一个合作电厂，将部分合作修改为全部合作
                        if(cSupplier.getCooperationRange().equals("section")){
                            List<Integer> powerId=service.queryAllPowerId(companyId);
                            List<Integer> powerSupplierId=service.queryPowerSupplierId(companyId,supplierId);
                            powerId.removeAll(powerSupplierId);
                            if(powerId.size()==0){
                                cSupplier.setCooperationRange("all");
                                cSupplier.setBlack(0);
                                service.updataCompanySupplier(cSupplier);
                            }
                        }
                    }
                }
                map.put("msg","申请审核通过");
            }else{//驳回申请
                map.put("msg","已驳回申请");
            }
            map.put("code", 200);
        }
        return map;
    }

    @RequestMapping("/blackApplyCheck")
    @ResponseBody
    public Object blackApplyCheck(BlackList blackList,BlackListCheck blackListCheck,HttpSession session){
        User user=(User)session.getAttribute("loginUser");
        Map<String,Object> map=new HashMap<>();
        if (user == null) {
            map.put("msg", "请先登录");
            map.put("code", 601);
        }else{
            service.updataBlackList(blackList);
            blackListCheck.setAuditorId(user.getId());
            service.saveBlackListCheck(blackListCheck);
            int companyId=user.getCompanyId();
            if(blackList.getAuditStatus().equals("agree")){
                CompanySupplier companySupplier=service.queryCompanySupplier(companyId,blackList.getSupplierId());
                if(companySupplier!=null){
                    companySupplier.setBlack(1);
                    service.updataCompanySupplier(companySupplier);
                    List<Integer> powerId=service.queryAllPowerId(companyId);
                    for (int id:powerId) {
                        service.updataPowerSupplierBlack(id,blackList.getSupplierId());
                    }
                }
                map.put("msg","申请审核通过");
            }else{//驳回申请
                map.put("msg","已驳回申请");
            }
            map.put("code", 200);
        }
        return map;
    }

    @RequestMapping("/updataSupplierType")
    @ResponseBody
    public Object updataSupplierType(int supplierId,String supplierType,HttpSession session){
        User user=(User)session.getAttribute("loginUser");
        Map<String,Object> map=new HashMap<>();
        if (user == null) {
            map.put("msg", "请先登录");
            map.put("code", 601);
        }else {
            CompanySupplier companySupplier=service.queryCompanySupplier(user.getCompanyId(),supplierId);
            if(companySupplier!=null){
                companySupplier.setSupplierType(supplierType);
                service.updataCompanySupplier(companySupplier);
                map.put("msg","申请审核通过");
                List<Integer> powerId=service.queryAllPowerId(user.getCompanyId());
                for (int id:powerId) {
                    service.updataPowerSupplierType(id,supplierId,supplierType);
                }
            }
            map.put("msg","修改成功");
            map.put("code", 200);
        }
        return map;
    }
}
